<%@page import="com.nxu.entity.BookBean"%>
<%@page import="com.nxu.biz.impl.BooksBizImpl"%>
<%@page import="com.nxu.biz.BooksBiz"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.io.File"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="java.util.*"%>

<%
// 检查是否是管理员
Boolean isAdmin = (Boolean) session.getAttribute("admin");
if (isAdmin == null || !isAdmin) {
    response.sendRedirect("login.jsp");
    return;
}

// 处理文件上传
String uploadPath = request.getServletContext().getRealPath("/") + "images";
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
    uploadDir.mkdir();
}

DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);

try {
    List<FileItem> items = upload.parseRequest(request);
    BookBean book = new BookBean();
    String fileName = null;
    
    for (FileItem item : items) {
        if (item.isFormField()) {
            String fieldName = item.getFieldName();
            String value = item.getString("UTF-8");
            
            switch (fieldName) {
                case "isbn":
                    book.setIsbn(value);
                    break;
                case "title":
                    book.setTitle(value);
                    break;
                case "copyright":
                    book.setCopyright(value);
                    break;
                case "editionnumber":
                    book.setEditionnumber(Integer.parseInt(value));
                    break;
                case "publisherid":
                    book.setPublisherid(Integer.parseInt(value));
                    break;
                case "price":
                    book.setPrice(Double.parseDouble(value));
                    break;
            }
        } else {
            if (!item.getName().isEmpty()) {
                fileName = new File(item.getName()).getName();
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);
                item.write(storeFile);
                book.setImagefile(fileName);
            }
        }
    }
    
    // 如果没有上传图片，设置默认图片
    if (book.getImagefile() == null || book.getImagefile().isEmpty()) {
        book.setImagefile("default.jpg");
    }
    
    BooksBiz biz = new BooksBizImpl();
    boolean success = biz.addBook(book);
    
    if (success) {
        response.sendRedirect("manage.jsp?msg=add_success");
    } else {
        response.sendRedirect("manage.jsp?msg=add_failed");
    }
} catch (Exception e) {
    e.printStackTrace();
    response.sendRedirect("manage.jsp?msg=error");
}
%>